<template>
  <div class="p-6 space-y-6">
    <!-- 共同目标进度 -->
    <div class="glass-effect rounded-3xl p-8 shadow-pink-xl">
      <h2 class="text-2xl font-bold text-pink-600 mb-6 flex items-center gap-2">
        <span>🎯</span>
        <span>共同目标</span>
      </h2>

      <div class="space-y-5">
        <div v-for="goal in goals" :key="goal.id" class="relative">
          <div class="flex items-center justify-between mb-2">
            <span class="text-pink-600 font-medium text-lg">{{ goal.title }}</span>
            <div class="flex items-center gap-3">
              <span class="text-pink-500 font-bold">{{ goal.progress }}%</span>
              <div class="flex gap-1">
                <n-button size="tiny" tertiary @click="handleEditGoal(goal)">
                  编辑
                </n-button>
                <n-button size="tiny" tertiary type="error" @click="handleDeleteGoal(goal.id)">
                  删除
                </n-button>
              </div>
            </div>
          </div>
          <n-progress
            type="line"
            :percentage="goal.progress"
            :color="'#FF6BB5'"
            :rail-color="'#FFE5EC'"
            :height="10"
            :border-radius="8"
          />
        </div>
      </div>

      <div class="mt-6 text-center">
        <n-button
          type="primary"
          size="large"
          class="rounded-xl bg-gradient-to-r from-pink-400 to-pink-500"
          @click="handleAddGoal"
        >
          + 添加新目标
        </n-button>
      </div>
    </div>

    <!-- 添加/编辑目标模态框 -->
    <n-modal v-model:show="showGoalModal">
      <div class="glass-effect rounded-3xl p-8 max-w-md w-full shadow-pink-xl">
        <h3 class="text-2xl font-bold text-pink-600 mb-6">
          {{ goalForm.id ? '编辑目标' : '添加目标' }}
        </h3>
        <n-form ref="goalFormRef" :model="goalForm" :rules="goalRules">
          <n-form-item label="目标名称" path="title">
            <n-input v-model:value="goalForm.title" placeholder="如：见面基金存钱计划" />
          </n-form-item>
          <n-form-item label="类型" path="type">
            <n-select
              v-model:value="goalForm.type"
              :options="[
                { label: '存钱', value: '存钱' },
                { label: '健身', value: '健身' },
                { label: '学习', value: '学习' },
                { label: '其他', value: '其他' },
              ]"
            />
          </n-form-item>
          <n-form-item label="目标值" path="target_value">
            <n-input-number
              v-model:value="goalForm.target_value"
              :min="1"
              placeholder="目标数值"
              class="w-full"
            />
          </n-form-item>
          <n-form-item label="当前值" path="current_value">
            <n-input-number
              v-model:value="goalForm.current_value"
              :min="0"
              placeholder="当前完成的数值"
              class="w-full"
            />
          </n-form-item>
          <n-form-item label="单位" path="unit">
            <n-input v-model:value="goalForm.unit" placeholder="如：元、次、天" />
          </n-form-item>
          <div class="flex gap-3">
            <n-button type="primary" size="large" block class="rounded-xl" @click="handleSaveGoal">
              {{ goalForm.id ? '保存' : '添加' }}
            </n-button>
            <n-button size="large" block class="rounded-xl" @click="showGoalModal = false">
              取消
            </n-button>
          </div>
        </n-form>
      </div>
    </n-modal>

    <!-- 添加/编辑愿望模态框 -->
    <n-modal v-model:show="showWishModal">
      <div class="glass-effect rounded-3xl p-8 max-w-md w-full shadow-pink-xl">
        <h3 class="text-2xl font-bold text-pink-600 mb-6">
          {{ wishForm.id ? '编辑愿望' : '添加愿望' }}
        </h3>
        <n-form ref="wishFormRef" :model="wishForm" :rules="wishRules">
          <n-form-item label="愿望内容" path="content">
            <n-input
              v-model:value="wishForm.content"
              type="textarea"
              placeholder="如：一起去看极光、一起学做饭..."
              :autosize="{ minRows: 3, maxRows: 6 }"
            />
          </n-form-item>
          <div class="flex gap-3">
            <n-button type="primary" size="large" block class="rounded-xl" @click="handleSaveWish">
              {{ wishForm.id ? '保存' : '添加' }}
            </n-button>
            <n-button size="large" block class="rounded-xl" @click="showWishModal = false">
              取消
            </n-button>
          </div>
        </n-form>
      </div>
    </n-modal>

    <!-- 添加/编辑礼物模态框 -->
    <n-modal v-model:show="showGiftModal">
      <div class="glass-effect rounded-3xl p-8 max-w-md w-full shadow-pink-xl">
        <h3 class="text-2xl font-bold text-pink-600 mb-6">
          {{ giftForm.id ? '编辑礼物' : '添加礼物' }}
        </h3>
        <n-form ref="giftFormRef" :model="giftForm" :rules="giftRules">
          <n-form-item label="礼物名称" path="title">
            <n-input v-model:value="giftForm.title" placeholder="如：香水、手表、书..." />
          </n-form-item>
          <n-form-item label="描述" path="description">
            <n-input
              v-model:value="giftForm.description"
              type="textarea"
              placeholder="礼物的详细描述（可选）"
              :autosize="{ minRows: 2, maxRows: 4 }"
            />
          </n-form-item>
          <n-form-item label="价格" path="price">
            <n-input-number
              v-model:value="giftForm.price"
              :min="0"
              placeholder="价格（可选）"
              class="w-full"
            >
              <template #prefix>¥</template>
            </n-input-number>
          </n-form-item>
          <n-form-item label="状态" path="status">
            <n-select
              v-model:value="giftForm.status"
              :options="[
                { label: '想要', value: '想要' },
                { label: '已送', value: '已送' },
                { label: '已收', value: '已收' },
              ]"
            />
          </n-form-item>
          <div class="flex gap-3">
            <n-button type="primary" size="large" block class="rounded-xl" @click="handleSaveGift">
              {{ giftForm.id ? '保存' : '添加' }}
            </n-button>
            <n-button size="large" block class="rounded-xl" @click="showGiftModal = false">
              取消
            </n-button>
          </div>
        </n-form>
      </div>
    </n-modal>

    <!-- 编辑统计信息模态框 -->
    <n-modal v-model:show="showStatsModal">
      <div class="glass-effect rounded-3xl p-8 max-w-md w-full shadow-pink-xl">
        <h3 class="text-2xl font-bold text-pink-600 mb-6">编辑恋爱统计</h3>
        <n-form ref="statsFormRef" :model="statsForm" :rules="statsRules">
          <n-form-item label="在一起日期" path="together_since">
            <n-date-picker
              v-model:formatted-value="statsForm.together_since"
              value-format="yyyy-MM-dd"
              type="date"
              class="w-full"
              placeholder="选择在一起的日期"
            />
          </n-form-item>
          <n-form-item label="初次见面日期" path="first_meet_date">
            <n-date-picker
              v-model:formatted-value="statsForm.first_meet_date"
              value-format="yyyy-MM-dd"
              type="date"
              class="w-full"
              placeholder="选择初次见面的日期（可选）"
              clearable
            />
          </n-form-item>
          <n-form-item label="见面次数" path="meet_count">
            <n-input-number
              v-model:value="statsForm.meet_count"
              :min="0"
              placeholder="见面次数"
              class="w-full"
            />
          </n-form-item>
          <div class="flex gap-3">
            <n-button type="primary" size="large" block class="rounded-xl" @click="handleSaveStats">
              保存
            </n-button>
            <n-button size="large" block class="rounded-xl" @click="showStatsModal = false">
              取消
            </n-button>
          </div>
        </n-form>
      </div>
    </n-modal>

    <!-- 编辑下次见面模态框 -->
    <n-modal v-model:show="showMeetingModal">
      <div class="glass-effect rounded-3xl p-8 max-w-md w-full shadow-pink-xl">
        <h3 class="text-2xl font-bold text-pink-600 mb-6">设置下次见面</h3>
        <n-form ref="meetingFormRef" :model="meetingForm" :rules="meetingRules">
          <n-form-item label="标题" path="title">
            <n-input v-model:value="meetingForm.title" placeholder="如：周末约会" />
          </n-form-item>
          <n-form-item label="见面日期" path="target_date">
            <n-date-picker
              v-model:formatted-value="meetingForm.target_date"
              value-format="yyyy-MM-dd HH:mm:ss"
              type="datetime"
              class="w-full"
              placeholder="选择见面日期和时间"
            />
          </n-form-item>
          <n-form-item label="备注" path="description">
            <n-input
              v-model:value="meetingForm.description"
              type="textarea"
              placeholder="见面计划（可选）"
              :autosize="{ minRows: 2, maxRows: 4 }"
            />
          </n-form-item>
          <div class="flex gap-3">
            <n-button type="primary" size="large" block class="rounded-xl" @click="handleSaveMeeting">
              保存
            </n-button>
            <n-button size="large" block class="rounded-xl" @click="showMeetingModal = false">
              取消
            </n-button>
          </div>
        </n-form>
      </div>
    </n-modal>

    <!-- 愿望清单 -->
    <div class="glass-effect rounded-3xl p-8 shadow-pink-xl">
      <h2 class="text-2xl font-bold text-pink-600 mb-6 flex items-center gap-2">
        <span>💰</span>
        <span>愿望清单</span>
      </h2>

      <div v-if="wishes.length === 0" class="text-center py-8">
        <p class="text-pink-400">还没有添加愿望，快来添加想一起做的事吧～</p>
      </div>

      <div v-else class="space-y-3">
        <div
          v-for="wish in wishes"
          :key="wish.id"
          class="glass-effect rounded-xl p-4 shadow-pink-sm hover:shadow-pink-md transition-all duration-300"
          :class="wish.is_completed ? 'opacity-60' : ''"
        >
          <div class="flex items-start gap-3">
            <n-checkbox
              :checked="wish.is_completed"
              size="large"
              @update:checked="handleToggleWish(wish.id, $event)"
            />
            <div class="flex-1">
              <p
                class="text-pink-600"
                :class="wish.is_completed ? 'line-through' : ''"
              >
                {{ wish.content }}
              </p>
              <div class="flex items-center gap-2 mt-2">
                <n-tag
                  v-if="wish.is_completed"
                  size="small"
                  type="success"
                  :bordered="false"
                >
                  已完成 ✓
                </n-tag>
                <span class="text-xs text-pink-400">
                  {{ formatDateDisplay(wish.created_at) }}
                </span>
              </div>
            </div>
            <div class="flex gap-1">
              <n-button size="tiny" tertiary @click="handleEditWish(wish)">
                编辑
              </n-button>
              <n-button size="tiny" tertiary type="error" @click="handleDeleteWish(wish.id)">
                删除
              </n-button>
            </div>
          </div>
        </div>
      </div>

      <div class="mt-6 text-center">
        <n-button
          type="primary"
          size="large"
          class="rounded-xl bg-gradient-to-r from-pink-400 to-pink-500"
          @click="handleAddWish"
        >
          + 添加新愿望
        </n-button>
      </div>
    </div>

    <!-- 礼物心愿单 -->
    <div class="glass-effect rounded-3xl p-8 shadow-pink-xl">
      <h2 class="text-2xl font-bold text-pink-600 mb-6 flex items-center gap-2">
        <span>🎁</span>
        <span>礼物心愿单</span>
      </h2>

      <div v-if="gifts.length === 0" class="text-center py-8">
        <p class="text-pink-400">还没有添加礼物记录，快来记录想要的礼物吧～</p>
      </div>

      <!-- 按状态分组显示礼物 -->
      <div v-else class="space-y-6">
        <!-- 想要的礼物 -->
        <div v-if="giftsByStatus.想要.length > 0">
          <h3 class="text-lg font-bold text-pink-500 mb-3 flex items-center gap-2">
            <span>💭</span>
            <span>想要的</span>
          </h3>
          <div class="space-y-3">
            <div
              v-for="gift in giftsByStatus.想要"
              :key="gift.id"
              class="glass-effect rounded-xl p-4 shadow-pink-sm hover:shadow-pink-md transition-all duration-300"
            >
              <div class="flex items-start gap-4">
                <div class="text-3xl">🎁</div>
                <div class="flex-1">
                  <div class="flex items-start justify-between mb-2">
                    <div>
                      <h4 class="text-pink-600 font-bold text-lg">{{ gift.title }}</h4>
                      <p v-if="gift.description" class="text-pink-500 text-sm mt-1">
                        {{ gift.description }}
                      </p>
                      <div class="flex items-center gap-3 mt-2">
                        <n-tag v-if="gift.price" size="small" type="warning" :bordered="false">
                          ¥{{ gift.price }}
                        </n-tag>
                        <n-tag size="small" type="default" :bordered="false">
                          {{ gift.status }}
                        </n-tag>
                      </div>
                    </div>
                    <div class="flex gap-1">
                      <n-button size="tiny" tertiary @click="handleEditGift(gift)">
                        编辑
                      </n-button>
                      <n-button size="tiny" tertiary type="error" @click="handleDeleteGift(gift.id)">
                        删除
                      </n-button>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>

        <!-- 已送的礼物 -->
        <div v-if="giftsByStatus.已送.length > 0">
          <h3 class="text-lg font-bold text-pink-500 mb-3 flex items-center gap-2">
            <span>🎀</span>
            <span>已送的</span>
          </h3>
          <div class="space-y-3">
            <div
              v-for="gift in giftsByStatus.已送"
              :key="gift.id"
              class="glass-effect rounded-xl p-4 shadow-pink-sm hover:shadow-pink-md transition-all duration-300"
            >
              <div class="flex items-start gap-4">
                <div class="text-3xl">💝</div>
                <div class="flex-1">
                  <div class="flex items-start justify-between mb-2">
                    <div>
                      <h4 class="text-pink-600 font-bold text-lg">{{ gift.title }}</h4>
                      <p v-if="gift.description" class="text-pink-500 text-sm mt-1">
                        {{ gift.description }}
                      </p>
                      <div class="flex items-center gap-3 mt-2">
                        <n-tag v-if="gift.price" size="small" type="warning" :bordered="false">
                          ¥{{ gift.price }}
                        </n-tag>
                        <n-tag size="small" type="success" :bordered="false">
                          {{ gift.status }}
                        </n-tag>
                      </div>
                    </div>
                    <div class="flex gap-1">
                      <n-button size="tiny" tertiary @click="handleEditGift(gift)">
                        编辑
                      </n-button>
                      <n-button size="tiny" tertiary type="error" @click="handleDeleteGift(gift.id)">
                        删除
                      </n-button>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>

        <!-- 已收的礼物 -->
        <div v-if="giftsByStatus.已收.length > 0">
          <h3 class="text-lg font-bold text-pink-500 mb-3 flex items-center gap-2">
            <span>🎉</span>
            <span>已收的</span>
          </h3>
          <div class="space-y-3">
            <div
              v-for="gift in giftsByStatus.已收"
              :key="gift.id"
              class="glass-effect rounded-xl p-4 shadow-pink-sm hover:shadow-pink-md transition-all duration-300"
            >
              <div class="flex items-start gap-4">
                <div class="text-3xl">🎊</div>
                <div class="flex-1">
                  <div class="flex items-start justify-between mb-2">
                    <div>
                      <h4 class="text-pink-600 font-bold text-lg">{{ gift.title }}</h4>
                      <p v-if="gift.description" class="text-pink-500 text-sm mt-1">
                        {{ gift.description }}
                      </p>
                      <div class="flex items-center gap-3 mt-2">
                        <n-tag v-if="gift.price" size="small" type="warning" :bordered="false">
                          ¥{{ gift.price }}
                        </n-tag>
                        <n-tag size="small" type="info" :bordered="false">
                          {{ gift.status }}
                        </n-tag>
                      </div>
                    </div>
                    <div class="flex gap-1">
                      <n-button size="tiny" tertiary @click="handleEditGift(gift)">
                        编辑
                      </n-button>
                      <n-button size="tiny" tertiary type="error" @click="handleDeleteGift(gift.id)">
                        删除
                      </n-button>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>

      <div class="mt-6 text-center">
        <n-button
          type="primary"
          size="large"
          class="rounded-xl bg-gradient-to-r from-pink-400 to-pink-500"
          @click="handleAddGift"
        >
          + 添加新礼物
        </n-button>
      </div>
    </div>

    <!-- 下次见面倒计时 -->
    <div class="glass-effect rounded-3xl p-8 shadow-pink-xl">
      <h2 class="text-2xl font-bold text-pink-600 mb-6 flex items-center gap-2">
        <span>💑</span>
        <span>下次见面倒计时</span>
      </h2>

      <div v-if="!meetingCountdown" class="text-center py-8">
        <p class="text-pink-400 mb-4">还没有设置下次见面时间</p>
        <n-button
          type="primary"
          size="large"
          class="rounded-xl bg-gradient-to-r from-pink-400 to-pink-500"
          @click="handleEditMeeting"
        >
          设置下次见面
        </n-button>
      </div>

      <div v-else class="space-y-4">
        <div class="glass-effect rounded-xl p-6 shadow-pink-sm text-center">
          <h3 class="text-pink-600 font-bold text-lg mb-4">{{ meetingCountdown.title }}</h3>
          <div class="flex items-center justify-center gap-4 mb-4">
            <div class="flex flex-col items-center">
              <span class="text-4xl font-bold text-pink-500">{{ meetingCountdownDisplay.days }}</span>
              <span class="text-sm text-pink-400 mt-1">天</span>
            </div>
            <span class="text-2xl text-pink-300">:</span>
            <div class="flex flex-col items-center">
              <span class="text-4xl font-bold text-pink-500">{{ meetingCountdownDisplay.hours }}</span>
              <span class="text-sm text-pink-400 mt-1">时</span>
            </div>
            <span class="text-2xl text-pink-300">:</span>
            <div class="flex flex-col items-center">
              <span class="text-4xl font-bold text-pink-500">{{ meetingCountdownDisplay.minutes }}</span>
              <span class="text-sm text-pink-400 mt-1">分</span>
            </div>
          </div>
          <p class="text-pink-500">
            {{ formatDateDisplay(meetingCountdown.target_date) }}
          </p>
          <p v-if="meetingCountdown.description" class="text-pink-400 text-sm mt-2">
            {{ meetingCountdown.description }}
          </p>
        </div>

        <div class="text-center">
          <n-button
            type="primary"
            size="large"
            class="rounded-xl bg-gradient-to-r from-pink-400 to-pink-500"
            @click="handleEditMeeting"
          >
            修改见面时间
          </n-button>
        </div>
      </div>
    </div>

    <!-- 详细统计 -->
    <div class="glass-effect rounded-3xl p-8 shadow-pink-xl">
      <h2 class="text-2xl font-bold text-pink-600 mb-6 flex items-center gap-2">
        <span>📊</span>
        <span>恋爱统计</span>
      </h2>

      <div v-if="!relationshipStat" class="text-center py-8">
        <p class="text-pink-400 mb-4">还没有设置恋爱统计信息</p>
        <n-button
          type="primary"
          size="large"
          class="rounded-xl bg-gradient-to-r from-pink-400 to-pink-500"
          @click="handleEditStats"
        >
          设置统计信息
        </n-button>
      </div>

      <div v-else class="space-y-6">
        <!-- 在一起天数 -->
        <div class="glass-effect rounded-xl p-6 shadow-pink-sm">
          <div class="flex items-center justify-between">
            <div class="flex items-center gap-3">
              <span class="text-4xl">💝</span>
              <div>
                <p class="text-pink-400 text-sm">在一起</p>
                <p class="text-3xl font-bold text-pink-600">{{ daysTogetherCount }}</p>
                <p class="text-pink-400 text-sm">天</p>
              </div>
            </div>
            <div class="text-right">
              <p class="text-pink-500 text-sm">开始日期</p>
              <p class="text-pink-600 font-medium">
                {{ formatDateDisplay(relationshipStat.together_since) }}
              </p>
            </div>
          </div>
        </div>

        <!-- 初次见面 -->
        <div v-if="relationshipStat.first_meet_date" class="glass-effect rounded-xl p-6 shadow-pink-sm">
          <div class="flex items-center gap-3">
            <span class="text-4xl">🌟</span>
            <div>
              <p class="text-pink-400 text-sm">初次见面</p>
              <p class="text-xl font-bold text-pink-600">
                {{ formatDateDisplay(relationshipStat.first_meet_date) }}
              </p>
              <p class="text-pink-400 text-sm">已经认识 {{ daysSinceMeet }} 天</p>
            </div>
          </div>
        </div>

        <!-- 见面次数 -->
        <div class="glass-effect rounded-xl p-6 shadow-pink-sm">
          <div class="flex items-center justify-between">
            <div class="flex items-center gap-3">
              <span class="text-4xl">👫</span>
              <div>
                <p class="text-pink-400 text-sm">见面次数</p>
                <p class="text-3xl font-bold text-pink-600">{{ relationshipStat.meet_count }}</p>
                <p class="text-pink-400 text-sm">次</p>
              </div>
            </div>
            <n-button
              size="small"
              type="primary"
              class="rounded-lg"
              @click="handleIncrementMeetCount"
            >
              + 1
            </n-button>
          </div>
        </div>

        <div class="text-center mt-6">
          <n-button
            type="primary"
            size="large"
            class="rounded-xl bg-gradient-to-r from-pink-400 to-pink-500"
            @click="handleEditStats"
          >
            编辑统计信息
          </n-button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, onUnmounted } from 'vue'
import { useMessage, useDialog, type FormInst, type FormRules } from 'naive-ui'
import { useAuthStore } from '@/stores/auth'
import * as goalApi from '@/api/goal'
import * as wishApi from '@/api/wish'
import * as giftApi from '@/api/gift'
import * as relationshipApi from '@/api/relationship'
import * as countdownApi from '@/api/countdown'
import type { Goal } from '@/types/goal'
import type { Wish } from '@/types/wish'
import type { Gift } from '@/types/gift'
import type { RelationshipStat } from '@/types/relationship'
import type { Countdown } from '@/types/countdown'

const message = useMessage()
const dialog = useDialog()
const loading = ref(false)

// 共同目标数据
const goalsData = ref<Goal[]>([])
const goals = computed(() =>
  goalsData.value.map((goal) => ({
    id: goal.id,
    title: goal.title,
    progress:
      goal.target_value > 0 ? Math.round((goal.current_value / goal.target_value) * 100) : 0,
    type: goal.type,
    unit: goal.unit,
    current_value: goal.current_value,
    target_value: goal.target_value,
    status: goal.status,
  })),
)

const loadGoals = async () => {
  try {
    goalsData.value = await goalApi.getGoals()
  } catch (error) {
    message.error('加载目标失败')
  }
}

// 目标表单
const showGoalModal = ref(false)
const goalFormRef = ref<FormInst | null>(null)
const goalForm = ref({
  id: null as number | null,
  title: '',
  type: '其他',
  target_value: 100,
  current_value: 0,
  unit: '',
})

const goalRules: FormRules = {
  title: [{ required: true, message: '请输入目标名称', trigger: 'blur' }],
  target_value: [{ required: true, message: '请输入目标值', trigger: 'blur', type: 'number' }],
}

// 添加目标
const handleAddGoal = () => {
  goalForm.value = {
    id: null,
    title: '',
    type: '其他',
    target_value: 100,
    current_value: 0,
    unit: '',
  }
  showGoalModal.value = true
}

// 编辑目标
const handleEditGoal = (goal: any) => {
  const goalData = goalsData.value.find((g) => g.id === goal.id)
  if (goalData) {
    goalForm.value = {
      id: goalData.id,
      title: goalData.title,
      type: goalData.type,
      target_value: goalData.target_value,
      current_value: goalData.current_value,
      unit: goalData.unit,
    }
    showGoalModal.value = true
  }
}

// 保存目标
const handleSaveGoal = async () => {
  if (!goalFormRef.value) return

  try {
    await goalFormRef.value.validate()

    if (goalForm.value.id) {
      // 编辑
      await goalApi.updateGoal(goalForm.value.id, {
        title: goalForm.value.title,
        type: goalForm.value.type,
        target_value: goalForm.value.target_value,
        current_value: goalForm.value.current_value,
        unit: goalForm.value.unit,
      })
      message.success('目标更新成功')
    } else {
      // 新增
      await goalApi.createGoal({
        title: goalForm.value.title,
        type: goalForm.value.type,
        target_value: goalForm.value.target_value,
        current_value: goalForm.value.current_value,
        unit: goalForm.value.unit,
      })
      message.success('目标添加成功')
    }

    showGoalModal.value = false
    await loadGoals()
  } catch (error) {
    message.error('保存目标失败')
  }
}

// 删除目标
const handleDeleteGoal = (id: number) => {
  dialog.warning({
    title: '确认删除',
    content: '确定要删除这个目标吗？',
    positiveText: '删除',
    negativeText: '取消',
    onPositiveClick: async () => {
      try {
        await goalApi.deleteGoal(id)
        message.success('目标已删除')
        await loadGoals()
      } catch (error) {
        message.error('删除目标失败')
      }
    },
  })
}

// ==================== 愿望清单功能 ====================
const authStore = useAuthStore()
const wishes = ref<Wish[]>([])

const loadWishes = async () => {
  try {
    wishes.value = await wishApi.getWishes()
  } catch (error) {
    message.error('加载愿望清单失败')
  }
}

// 愿望表单
const showWishModal = ref(false)
const wishFormRef = ref<FormInst | null>(null)
const wishForm = ref({
  id: null as number | null,
  content: '',
})

const wishRules: FormRules = {
  content: [{ required: true, message: '请输入愿望内容', trigger: 'blur' }],
}

// 添加愿望
const handleAddWish = () => {
  wishForm.value = {
    id: null,
    content: '',
  }
  showWishModal.value = true
}

// 编辑愿望
const handleEditWish = (wish: Wish) => {
  wishForm.value = {
    id: wish.id,
    content: wish.content,
  }
  showWishModal.value = true
}

// 保存愿望
const handleSaveWish = async () => {
  if (!wishFormRef.value) return

  try {
    await wishFormRef.value.validate()
    const userId = authStore.userInfo?.id
    if (!userId) {
      message.error('用户信息获取失败')
      return
    }

    if (wishForm.value.id) {
      // 编辑
      await wishApi.updateWish(wishForm.value.id, {
        content: wishForm.value.content,
      })
      message.success('愿望更新成功')
    } else {
      // 新增
      await wishApi.createWish({
        content: wishForm.value.content,
        creator_id: userId,
      })
      message.success('愿望添加成功')
    }

    showWishModal.value = false
    await loadWishes()
  } catch (error) {
    message.error('保存愿望失败')
  }
}

// 切换愿望完成状态
const handleToggleWish = async (id: number, completed: boolean) => {
  try {
    await wishApi.updateWish(id, { is_completed: completed })
    message.success(completed ? '愿望已完成 🎉' : '愿望标记为未完成')
    await loadWishes()
  } catch (error) {
    message.error('更新愿望状态失败')
  }
}

// 删除愿望
const handleDeleteWish = (id: number) => {
  dialog.warning({
    title: '确认删除',
    content: '确定要删除这个愿望吗？',
    positiveText: '删除',
    negativeText: '取消',
    onPositiveClick: async () => {
      try {
        await wishApi.deleteWish(id)
        message.success('愿望已删除')
        await loadWishes()
      } catch (error) {
        message.error('删除愿望失败')
      }
    },
  })
}

// ==================== 礼物心愿单功能 ====================
const gifts = ref<Gift[]>([])

// 按状态分组礼物
const giftsByStatus = computed(() => {
  return {
    想要: gifts.value.filter((g) => g.status === '想要'),
    已送: gifts.value.filter((g) => g.status === '已送'),
    已收: gifts.value.filter((g) => g.status === '已收'),
  }
})

const loadGifts = async () => {
  try {
    gifts.value = await giftApi.getGifts()
  } catch (error) {
    message.error('加载礼物清单失败')
  }
}

// 礼物表单
const showGiftModal = ref(false)
const giftFormRef = ref<FormInst | null>(null)
const giftForm = ref({
  id: null as number | null,
  title: '',
  description: '',
  price: undefined as number | undefined,
  status: '想要',
})

const giftRules: FormRules = {
  title: [{ required: true, message: '请输入礼物名称', trigger: 'blur' }],
  status: [{ required: true, message: '请选择状态', trigger: 'blur' }],
}

// 添加礼物
const handleAddGift = () => {
  const userId = authStore.userInfo?.id
  if (!userId) {
    message.error('用户信息获取失败')
    return
  }

  giftForm.value = {
    id: null,
    title: '',
    description: '',
    price: undefined,
    status: '想要',
  }
  showGiftModal.value = true
}

// 编辑礼物
const handleEditGift = (gift: Gift) => {
  giftForm.value = {
    id: gift.id,
    title: gift.title,
    description: gift.description || '',
    price: gift.price,
    status: gift.status,
  }
  showGiftModal.value = true
}

// 保存礼物
const handleSaveGift = async () => {
  if (!giftFormRef.value) return

  try {
    await giftFormRef.value.validate()
    const userId = authStore.userInfo?.id
    if (!userId) {
      message.error('用户信息获取失败')
      return
    }

    const giftData = {
      title: giftForm.value.title,
      description: giftForm.value.description || undefined,
      price: giftForm.value.price,
      status: giftForm.value.status,
    }

    if (giftForm.value.id) {
      // 编辑
      await giftApi.updateGift(giftForm.value.id, giftData)
      message.success('礼物更新成功')
    } else {
      // 新增
      await giftApi.createGift({
        ...giftData,
        to_user_id: userId,
      })
      message.success('礼物添加成功')
    }

    showGiftModal.value = false
    await loadGifts()
  } catch (error) {
    message.error('保存礼物失败')
  }
}

// 删除礼物
const handleDeleteGift = (id: number) => {
  dialog.warning({
    title: '确认删除',
    content: '确定要删除这个礼物记录吗？',
    positiveText: '删除',
    negativeText: '取消',
    onPositiveClick: async () => {
      try {
        await giftApi.deleteGift(id)
        message.success('礼物已删除')
        await loadGifts()
      } catch (error) {
        message.error('删除礼物失败')
      }
    },
  })
}

// ==================== 恋爱统计功能 ====================
const relationshipStat = ref<RelationshipStat | null>(null)

// 在一起天数
const daysTogetherCount = computed(() => {
  if (!relationshipStat.value?.together_since) return 0
  const togetherDate = new Date(relationshipStat.value.together_since)
  if (isNaN(togetherDate.getTime())) return 0
  const today = new Date()
  const diffTime = Math.abs(today.getTime() - togetherDate.getTime())
  return Math.ceil(diffTime / (1000 * 60 * 60 * 24))
})

// 认识天数
const daysSinceMeet = computed(() => {
  if (!relationshipStat.value?.first_meet_date) return 0
  const meetDate = new Date(relationshipStat.value.first_meet_date)
  if (isNaN(meetDate.getTime())) return 0
  const today = new Date()
  const diffTime = Math.abs(today.getTime() - meetDate.getTime())
  return Math.ceil(diffTime / (1000 * 60 * 60 * 24))
})

const loadRelationshipStats = async () => {
  try {
    const stats = await relationshipApi.getRelationshipStats()
    // 获取第一条记录（假设只有一条统计记录）
    if (stats.length > 0) {
      relationshipStat.value = stats[0]
    }
  } catch (error) {
    console.error('加载恋爱统计失败', error)
  }
}

// 统计信息表单
const showStatsModal = ref(false)
const statsFormRef = ref<FormInst | null>(null)
type StatsFormState = {
  together_since: string | null
  first_meet_date: string | null
  meet_count: number
}
const statsForm = ref<StatsFormState>({
  together_since: null,
  first_meet_date: null,
  meet_count: 0,
})

const statsRules: FormRules = {
  together_since: [{ required: true, message: '请选择在一起的日期', trigger: 'blur' }],
  meet_count: [{ required: true, message: '请输入见面次数', trigger: 'blur', type: 'number' }],
}

// 安全地格式化日期用于显示（模板中使用）
const formatDateDisplay = (dateValue: string | null | undefined): string => {
  if (!dateValue) return ''

  try {
    const date = new Date(dateValue)
    if (isNaN(date.getTime())) {
      return ''
    }
    return date.toLocaleDateString('zh-CN')
  } catch {
    return ''
  }
}

// 安全地格式化日期为 yyyy-MM-dd 格式
const formatDateToString = (dateValue: string | null | undefined): string | null => {
  console.log('[formatDateToString] 输入值:', dateValue, '类型:', typeof dateValue)

  if (!dateValue) {
    console.log('[formatDateToString] 输入值为空，返回 null')
    return null
  }

  try {
    // 如果已经是 yyyy-MM-dd 格式，直接返回
    if (/^\d{4}-\d{2}-\d{2}$/.test(dateValue)) {
      console.log('[formatDateToString] 已经是标准格式，直接返回:', dateValue)
      return dateValue
    }

    // 如果是 ISO 格式（包含 T），提取日期部分
    if (dateValue.includes('T')) {
      const result = dateValue.split('T')[0]
      console.log('[formatDateToString] ISO 格式，提取日期部分:', result)
      return result
    }

    // 尝试解析为 Date 对象
    const date = new Date(dateValue)
    console.log('[formatDateToString] 创建 Date 对象:', date, 'getTime():', date.getTime())

    if (isNaN(date.getTime())) {
      console.warn('[formatDateToString] 日期无效，返回 null')
      return null
    }

    // 格式化为 yyyy-MM-dd
    const result = `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`
    console.log('[formatDateToString] 格式化结果:', result)
    return result
  } catch (error) {
    console.error('[formatDateToString] 日期格式化失败:', error, '输入值:', dateValue)
    return null
  }
}

// 编辑统计信息
const handleEditStats = () => {
  console.log('[handleEditStats] 开始编辑统计信息')
  console.log('[handleEditStats] relationshipStat.value:', relationshipStat.value)

  if (relationshipStat.value) {
    console.log('[handleEditStats] together_since 原始值:', relationshipStat.value.together_since)
    console.log('[handleEditStats] first_meet_date 原始值:', relationshipStat.value.first_meet_date)

    statsForm.value = {
      together_since: formatDateToString(relationshipStat.value.together_since),
      first_meet_date: formatDateToString(relationshipStat.value.first_meet_date),
      meet_count: relationshipStat.value.meet_count,
    }

    console.log('[handleEditStats] 表单赋值后:', statsForm.value)
  } else {
    statsForm.value = {
      together_since: null,
      first_meet_date: null,
      meet_count: 0,
    }
  }
  showStatsModal.value = true
}

// 保存统计信息
const handleSaveStats = async () => {
  if (!statsFormRef.value) return

  try {
    await statsFormRef.value.validate()

    const { together_since, first_meet_date, meet_count } = statsForm.value

    if (!together_since) {
      message.error('请选择在一起的日期')
      return
    }

    const statsData = {
      together_since,
      first_meet_date: first_meet_date || undefined,
      meet_count,
    }

    if (relationshipStat.value) {
      // 更新
      await relationshipApi.updateRelationshipStat(relationshipStat.value.id, statsData)
      message.success('统计信息更新成功')
    } else {
      // 创建
      await relationshipApi.createRelationshipStat(statsData)
      message.success('统计信息创建成功')
    }

    showStatsModal.value = false
    await loadRelationshipStats()
  } catch (error) {
    message.error('保存统计信息失败')
  }
}

// 增加见面次数
const handleIncrementMeetCount = async () => {
  if (!relationshipStat.value) return

  try {
    await relationshipApi.updateRelationshipStat(relationshipStat.value.id, {
      meet_count: relationshipStat.value.meet_count + 1,
    })
    message.success('见面次数 +1 🎉')
    await loadRelationshipStats()
  } catch (error) {
    message.error('更新见面次数失败')
  }
}

// ==================== 下次见面倒计时功能 ====================
const meetingCountdown = ref<Countdown | null>(null)
let countdownTimer: number | null = null

// 倒计时显示数据
const meetingCountdownDisplay = computed(() => {
  if (!meetingCountdown.value?.target_date) {
    return {
      days: 0,
      hours: 0,
      minutes: 0,
    }
  }

  const now = new Date().getTime()
  const target = new Date(meetingCountdown.value.target_date).getTime()

  // 检查日期是否有效
  if (isNaN(target)) {
    return {
      days: 0,
      hours: 0,
      minutes: 0,
    }
  }

  const diff = target - now

  if (diff <= 0) {
    return {
      days: 0,
      hours: 0,
      minutes: 0,
    }
  }

  const days = Math.floor(diff / (1000 * 60 * 60 * 24))
  const hours = Math.floor((diff % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60))
  const minutes = Math.floor((diff % (1000 * 60 * 60)) / (1000 * 60))

  return {
    days,
    hours,
    minutes,
  }
})

const loadMeetingCountdown = async () => {
  try {
    const countdowns = await countdownApi.getCountdowns()
    // 获取第一个"见面"类型的倒计时
    meetingCountdown.value = countdowns.find((c: Countdown) => c.type === '见面') || null
  } catch (error) {
    console.error('加载见面倒计时失败', error)
  }
}

// 见面倒计时表单
const showMeetingModal = ref(false)
const meetingFormRef = ref<FormInst | null>(null)
type MeetingFormState = {
  title: string
  target_date: string | null
  description: string
}
const meetingForm = ref<MeetingFormState>({
  title: '',
  target_date: null,
  description: '',
})

const meetingRules: FormRules = {
  title: [{ required: true, message: '请输入标题', trigger: 'blur' }],
  target_date: [{ required: true, message: '请选择见面日期', trigger: 'blur' }],
}

// 安全地格式化日期时间为 yyyy-MM-dd HH:mm:ss 格式
const formatDateTimeToString = (dateValue: string | null | undefined): string | null => {
  console.log('[formatDateTimeToString] 输入值:', dateValue, '类型:', typeof dateValue)

  if (!dateValue) {
    console.log('[formatDateTimeToString] 输入值为空，返回 null')
    return null
  }

  try {
    const date = new Date(dateValue)
    console.log('[formatDateTimeToString] 创建 Date 对象:', date, 'getTime():', date.getTime())

    if (isNaN(date.getTime())) {
      console.warn('[formatDateTimeToString] 日期无效，返回 null')
      return null
    }

    const result = `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}:${String(date.getSeconds()).padStart(2, '0')}`
    console.log('[formatDateTimeToString] 格式化结果:', result)
    return result
  } catch (error) {
    console.error('[formatDateTimeToString] 日期时间格式化失败:', error, '输入值:', dateValue)
    return null
  }
}

// 编辑见面倒计时
const handleEditMeeting = () => {
  console.log('[handleEditMeeting] 开始编辑见面倒计时')
  console.log('[handleEditMeeting] meetingCountdown.value:', meetingCountdown.value)

  if (meetingCountdown.value) {
    console.log('[handleEditMeeting] target_date 原始值:', meetingCountdown.value.target_date)

    meetingForm.value = {
      title: meetingCountdown.value.title,
      target_date: formatDateTimeToString(meetingCountdown.value.target_date),
      description: meetingCountdown.value.description || '',
    }

    console.log('[handleEditMeeting] 表单赋值后:', meetingForm.value)
  } else {
    // 创建模式
    meetingForm.value = {
      title: '下次见面',
      target_date: null,
      description: '',
    }
  }
  showMeetingModal.value = true
}

// 保存见面倒计时
const handleSaveMeeting = async () => {
  if (!meetingFormRef.value) return

  try {
    await meetingFormRef.value.validate()
    const userId = authStore.userInfo?.id
    if (!userId) {
      message.error('用户信息获取失败')
      return
    }

    const { title, target_date, description } = meetingForm.value

    if (!target_date) {
      message.error('请选择见面日期')
      return
    }

    const meetingData = {
      title,
      target_date, // 使用 "yyyy-MM-dd HH:mm:ss" 格式
      description: description || undefined,
      type: '见面',
    }

    if (meetingCountdown.value) {
      // 更新
      await countdownApi.updateCountdown(meetingCountdown.value.id, meetingData)
      message.success('见面倒计时更新成功')
    } else {
      // 创建
      await countdownApi.createCountdown({
        ...meetingData,
        creator_id: userId,
      })
      message.success('见面倒计时创建成功')
    }

    showMeetingModal.value = false
    await loadMeetingCountdown()
  } catch (error) {
    message.error('保存见面倒计时失败')
  }
}

// 启动倒计时定时器
const startCountdownTimer = () => {
  // 每分钟更新一次倒计时
  countdownTimer = window.setInterval(() => {
    if (meetingCountdown.value) {
      // 强制重新计算 computed
      meetingCountdown.value = { ...meetingCountdown.value }
    }
  }, 60000)
}

// 页面加载
onMounted(async () => {
  loading.value = true
  try {
    await Promise.all([
      loadGoals(),
      loadWishes(),
      loadGifts(),
      loadRelationshipStats(),
      loadMeetingCountdown(),
    ])
    startCountdownTimer()
  } finally {
    loading.value = false
  }
})

// 组件卸载时清除定时器
onUnmounted(() => {
  if (countdownTimer) {
    clearInterval(countdownTimer)
  }
})
</script>
